package com.gecba.system.service.impl;

import com.gecba.modular.jpa.service.impl.ServiceImpl;
import com.gecba.system.dao.repository.SysRoleRepository;
import com.gecba.system.entity.SysRole;
import com.gecba.system.service.SysRoleService;
import com.gecba.system.vo.SearchVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author ChenBo
 * @className SysRoleServiceImpl
 * @date 2021/7/25
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleRepository,SysRole,Long> implements SysRoleService {


    @Autowired
    private SysRoleRepository roleRepository;

    /**
     * 分页查询
     *
     * @param sysRole
     * @param searchVO
     * @param pageable
     * @return
     */
    @Override
    public Page<SysRole> pageList(SysRole sysRole, SearchVO searchVO, Pageable pageable) {


        Specification<SysRole> specification = (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();

            if(StringUtils.isNotBlank(sysRole.getRoleName())){
                predicates.add(criteriaBuilder.like(root.get("roleName"), "%"+sysRole.getRoleName()+"%"));
            }

            if(StringUtils.isNotBlank(sysRole.getRoleCode())){
                predicates.add(criteriaBuilder.equal(root.get("roleCode"), sysRole.getRoleCode()));
            }

            if(StringUtils.isNotBlank(sysRole.getDescription())){
                predicates.add(criteriaBuilder.like(root.get("description"), "%"+sysRole.getDescription()+"%"));
            }

            if(Objects.nonNull(sysRole.getStatus())){
                predicates.add(criteriaBuilder.equal(root.get("status"), sysRole.getDescription()));
            }

            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        };

        return roleRepository.findAll(specification, pageable);
    }
}
